// import domains from './domains.js'
import domains from './httpUrl.js'
import Cookie from "js-cookie";
export default {
	request({
		url,
		method,
		data,
		loading,
		dataType,
		headers,
		success,
		error,
		complete
	}) {
		if (!data) {
			data = {}
		}
		// var loginInfo = content.loginInfo
		var token = data.token || Cookie.get('Token')

		/* var token = '' */
		// if (loginInfo) {
		// token = loginInfo.token
		//     data.shopId = loginInfo.shopId
		//     data.memId = loginInfo.memId
		//     data.empId = loginInfo.empId
		// }
		let options = {}
		//默认method
		options['method'] = method || 'POST'
		options['dataType'] = dataType || 'json'
		//默认header
		options['headers'] = Object.assign({
			'Content-Type': 'application/x-www-form-urlencoded', //默认格式
			// 'credentials': 'include', //包含cookie
			// 'mode': 'cors', //允许跨域
			'accessToken': token
		}, headers)
		options['timeout'] = 15000
		// 处理body
		options['body'] = formatData(headers, data)
		// if (!hidden) {
		//     EasyLoading.show()
		// }
		fetch(domains.pro1 + url, options).then((response) =>
			response.json()
		).then((responseJson) => {
			let res = responseJson
			if (res) {
				res.state == 1 && success(res.data)
				if (error && res.state != 1) {
					error(res)
				}
			}
			if (complete) {
				complete()
			}
			// EasyLoading.dismiss()
		}).catch((err) => {
			if (error && err.state != 1) {
				error(err)
			}
			if (complete) {
				complete()
			}
			// EasyLoading.dismiss()
		})
	}
}

function toForm(data) {
	var formData = null
	Object.keys(data).forEach((key) => {
		if (formData) {
			formData = formData + '&' + key + '=' + data[key]
		} else {
			formData = key + '=' + data[key]
		}
	});
	return formData
}

function toJsonStr(data) {
	return JSON.stringify(data)
}

function formatData(headers, data) {
	if (!headers || !headers['Content-Type'] || headers['Content-Type'] === 'application/x-www-form-urlencoded') {
		return toForm(data)
	}
	switch (headers['Content-Type']) {
		case 'application/json':
			return toJsonStr(data)
		default:
			return toForm(data)
	}
}
